//
//  ViewController.m
//  HaiYue
//
//  Created by tucici on 2019/4/2.
//  Copyright © 2019 skyline. All rights reserved.
//

#import "ViewController.h"
#import <CCKit/CCKit.h>


@interface ViewController ()<NSURLSessionDelegate>
{
    UIWindow *_window;
}
@property (nonatomic, strong) UIButton *downloadBtn;
@property (nonatomic, strong) UIButton *pauseBtn;
@property (nonatomic, strong) UIButton *jixuBtn;
@property (nonatomic, strong) HYHud *hud;
@property (nonatomic, strong) NSURLSessionDownloadTask *task;
@property (nonatomic, strong) NSData *data;
@property (nonatomic, strong) NSMutableData *recivedata;
@property (nonatomic, strong) NSURLSession *session;

@end

@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    CGFloat i = 0.1;
    self.view.backgroundColor = [UIColor whiteColor];
   

    // Do any additional setup after loading the view.
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
}
- (void)actionforDown:(UIButton *)sender
{
//    [CCHud hud].color = THEME_COLOR;
//    [CCHud hud].backgroundColor = BLUE_COLOR;
//    [CCHud startHud];
//        [CCHud startHud:@"正在加载.."];
    return;
    // 1. URL
    //    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    //        self.session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
    //    NSURL *URL = [NSURL URLWithString:@"https://dl.ddgame37.com/download/apk/bravehuawei.apk"];
    //
    //    self.task = [self.session downloadTaskWithRequest:[NSURLRequest requestWithURL:URL]];
    //    // 3. 启动下载任务
    //    [self.task resume];
    //
    //    return;
    
    self.task = [CCHttp download:@"https://dl.ddgame37.com/download/apk/bravehuawei.apk" para:nil progress:^(NSURLSession *_Nonnull session, NSProgress * _Nonnull progress) {
        self.session = session;
        NSLog(@"progress == %@",progress.localizedDescription);
    } success:^(id  _Nonnull response) {
        NSLog(@"response == %@",response);
    } fail:^(NSError * _Nonnull error) {
        NSLog(@"fail == %@",error);
    }];
}
- (void)actionforPause:(UIButton *)sender
{

    [CCHud startHud:@"网络不佳，超时，请稍后再试...续传数据,当暂停下载之后,会把续传的数据回调出去,方便我们做断点下载续传数据,当暂停下载之后,会把续传的数据回调出去,方便我们做断点下载续传数据,当暂停下载之后,会把续传的数据回调出去,方便我们做断点下载xxxxx方便我们做断点下载x方便我们做断点下载x方便我们做断点下载x方便我们做断点下载x"];
    return
    [self.task cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
        // resumeData : 续传数据,当暂停下载之后,会把续传的数据回调出去,方便我们做断点下载
        // resumeData : 已经下载的字节数...
        self.data = resumeData;
        
        // 拿到续传数据之后,把续传数据保存在沙盒中,APP重启之后,就可以继续下载
        NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"resume.data"];
        [resumeData writeToFile:fullPath atomically:YES];
        
        // 当我们第一次点击暂停时,会成功的回调resumeData数据,但是再次点击时,就回调一个空的resumeData
        NSLog(@"%tu",resumeData.length);
        
        // 为了避免第二次点击暂停时,resumeData为空,
        self.task = nil;
    }];
}
- (void)actionforJX:(UIButton *)sender
{
    [CCHud startHud:@"当暂停下载之后,会把续传的数据回调出去,方便我们做断点下便我们做断点下便"];
    return;
    if (self.data != nil && self.task == nil)
    {
        //        self.task = [self.session downloadTaskWithResumeData:self.data];
        //        // 重新发起续传任务时,也要手动的启动任务
        //        [self.task resume];
        //
        //        return;
        self.task = [CCHttp downloadTaskWithResumeData:self.data session:self.session];
        // 重新发起续传任务时,也要手动的启动任务
        self.data = nil;
        NSLog(@"继续");
    }
    
}
#pragma mark -- NSURLSessionDownloadDelegate
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
    [self.recivedata appendData:data];
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(nullable NSError *)error
{
    if (error)
    {
        return;
    }
    NSError *dicError = nil;
    
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:self.recivedata options:NSJSONReadingMutableLeaves error:&dicError];
    NSString *sting = [[NSString alloc] initWithData:self.recivedata encoding:NSUTF8StringEncoding];
    
    if (dicError)
    {
        return;
    }
    [session finishTasksAndInvalidate];
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    CGFloat f = 100.0 *totalBytesWritten / totalBytesExpectedToWrite;
    NSString *f_str1 = [NSString stringWithFormat:@"%.2f",f];
    f_str1 = [f_str1 stringByAppendingString:@"%"];
    NSLog(@"已经下载  = %@",f_str1);
    
}

- (HYHud *)hud
{
    if (!_hud)
    {
        _hud = [HYHud hud];
        _hud.color = THEME_COLOR;
    }
    return _hud;
}
- (UIButton *)downloadBtn
{
    if (!_downloadBtn)
    {
        _downloadBtn = [[UIButton alloc] init];
        _downloadBtn.backgroundColor = [UIColor purpleColor];
        [_downloadBtn setTitle:@"下载" forState:UIControlStateNormal];
        [_downloadBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_downloadBtn addTarget:self action:@selector(actionforDown:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_downloadBtn];
        _downloadBtn.c_height.c_equal(nil).with.coffset(40);
        _downloadBtn.c_width.c_equal(50);
        _downloadBtn.c_left.c_equal(self.jixuBtn.c_right).with.coffset(0);
        _downloadBtn.c_top.c_equal(self.view).with.coffset(30);
        _downloadBtn.c_top.c_equal(self.pauseBtn.c_bottom).with.coffset(0);
        _downloadBtn.c_size.c_equal(nil).with.coffset(CGSizeMake(100.5, 123.8));
//        _downloadBtn.edges.c_equal(self.view).with.coffset(UIEdgeInsetsZero);
    }
    return _downloadBtn;
}
- (UIButton *)pauseBtn
{
    if (!_pauseBtn)
    {
        _pauseBtn = [[UIButton alloc] initWithFrame:CGRectMake(70, 20, 50, 40)];
        _pauseBtn.backgroundColor = [UIColor purpleColor];
        [_pauseBtn setTitle:@"暂停" forState:UIControlStateNormal];
        [_pauseBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_pauseBtn addTarget:self action:@selector(actionforPause:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_pauseBtn];
    }
    return _pauseBtn;
}
- (UIButton *)jixuBtn
{
    if (!_jixuBtn)
    {
        _jixuBtn = [[UIButton alloc] initWithFrame:CGRectMake(130, 20, 50, 40)];
        _jixuBtn.backgroundColor = [UIColor purpleColor];
        [_jixuBtn setTitle:@"继续" forState:UIControlStateNormal];
        [_jixuBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_jixuBtn addTarget:self action:@selector(actionforJX:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_jixuBtn];
    }
    return _jixuBtn;
}

- (void)dealloc
{
    NSLog(@"dealloc -============");
}
/*
 
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
